﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
using System.IO;



namespace SampleWinProject.Printer
{
    public partial class frmPrinter : Form
    {
        System.Threading.Thread thread;
        private System.Collections.Generic.Queue<String> fileList = new System.Collections.Generic.Queue<String>();
        private String templete;
        private Boolean printed = true;

        public frmPrinter()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 监控文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void fileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e)
        {
            //将文件添加到待打印列表中
           fileList.Enqueue(Properties.Settings.Default.PrintFolder + e.Name);
           //监听到文件
           this.AppendLog("监听到订单" + e.Name);
           
            
        }

        private void AppendLog(String log)
        {
            txtLog.Invoke(new EventHandler(AppendLog), log, EventArgs.Empty);
           
        }


        private void AppendLog(object sender, EventArgs e)
        {
            if(sender != null)
                txtLog.AppendText(String.Format("{0}:{1}\r\n",DateTime.Now.ToString("yyyy-MM-dd HH:mm"),sender));
        }

        private void frmPrinter_Load(object sender, EventArgs e)
        {
            this.AppendLog("应用启动中。。。");
            StreamReader reader = null;
            try
            {
                reader = File.OpenText(Properties.Settings.Default.PrintFolder + "\\Templete\\templete.htm");
                templete = reader.ReadToEnd();
            }
            catch (FileNotFoundException err)
            {
                this.AppendLog(String.Format("模板文件未找到，将影响到打印的正常进行,请重新检测模板文件{0}并启动程序",Properties.Settings.Default.PrintFolder + "\\Templete\\templete.htm"));
            }
            catch (Exception err)
            {
                this.AppendLog("错误信息：" + err.Message);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                    reader.Dispose();
                    reader = null;

                }
            }

         
            this.fileSystemWatcher1.Path = Properties.Settings.Default.PrintFolder;
            fileSystemWatcher1.InitializeLifetimeService();
            //启动的时候，如果发现有存在的文件就加载到列表中
            foreach (string file in System.IO.Directory.GetFiles(Properties.Settings.Default.PrintFolder))
            {
                fileList.Enqueue(file);
            }
            if(fileList.Count>0)
                this.AppendLog(String.Format("共找到{0}个待打印订单",fileList.Count));
            thread = new System.Threading.Thread(new System.Threading.ThreadStart(Run));
            thread.Priority = System.Threading.ThreadPriority.Lowest;
            thread.SetApartmentState(System.Threading.ApartmentState.STA);
            thread.Start();
            this.AppendLog("启动完成！");
        }

        /// <summary>
        /// 将日期字符串转换成指定格式日期字符串
        /// </summary>
        /// <param name="time"></param>
        /// <param name="sourceformat">源格式</param>
        /// <param name="targetformat">目标格式</param>
        /// <returns>返回指定格式字符串</returns>
        public static string GetDateTime(string time, string sourceformat, string targetformat)
        {

            try
            {
                if (sourceformat == "")
                    sourceformat = "yyyyMMddHHmmss";
                if (targetformat == "")
                    targetformat = "yyyy-MM-dd";
                time = DateTime.ParseExact(time, sourceformat, global::System.Globalization.CultureInfo.CurrentCulture
                    , global::System.Globalization.DateTimeStyles.None).ToString(targetformat);
            }
            catch (Exception ex)
            {
                time = "";
            }
            return time;
        }

        private bool Print(String FileName)
        {

            //读取该文件
            String json;
            StreamReader reader = null;
            try
            {
                reader = File.OpenText(FileName);
                json = reader.ReadToEnd();
            }
            catch (Exception err)
            {
                this.AppendLog("错误信息：" + err.Message);
                return false;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                    reader.Dispose();
                    reader = null;

                }
            }
            Newtonsoft.Json.Linq.JObject obj = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(json);

            String type = obj["DELIVERY_TYPE"].ToString();
            if (type == "1")
            {
                type = "客户自提";
            }
            else if (type == "2")
            {
                type = "送货上门";
            }
            else if (type == "3")
            {
                type = "委托快递";
            }
            else
            {
                type = "客户自提";
            }

            StringBuilder product = new StringBuilder();

            var LINES = obj["LINES"] as Newtonsoft.Json.Linq.JArray;
            if (LINES != null)
            {
                foreach (var line in LINES)
                {

                    float price = float.Parse(line["PRICE"].ToString());
                    int quantity = int.Parse(line["QUANTITY_ORDERED"].ToString());
                    product.AppendFormat("<tr><td>{0}</td><td style='text-align:center;'>{1}</td><td style='text-align:center;'>{2}</td><td style='text-align:center;'>{3}</td><td style='text-align:center;'>{4}</td></tr>", line["DESCRIPTION"] != null ? line["DESCRIPTION"].ToString() : "", line["CODE"] != null ? line["CODE"].ToString() : "", price, quantity, price * quantity);
                }
            }
            float TOTAL_AMOUNT = float.Parse(obj["TOTAL_AMOUNT"].ToString());
            float DISC_AMOUNT = float.Parse(obj["DISC_AMOUNT"].ToString());
            float EXTENDED_AMOUNT = float.Parse(obj["EXTENDED_AMOUNT"].ToString());
            //插入合计应付金额
            product.AppendFormat("<tr><td colspan=2>&nbsp</td><td colspan=2 style='text-align:center;'>合计应付:</td><td style='text-align:center;'>{0}</td></tr>", TOTAL_AMOUNT);

            //插入折扣金额
            if (DISC_AMOUNT > 0)
            {
                product.AppendFormat("<tr><td colspan=2>&nbsp</td><td colspan=2 style='text-align:center;'>折扣金额</td><td style='text-align:center;'>-{0}</td></tr>", DISC_AMOUNT);
            }
            //插入已付金额
            if (EXTENDED_AMOUNT > 0)
            {
                product.AppendFormat("<tr><td colspan=2>&nbsp</td><td colspan=2 style='text-align:center;'>已付金额:</td><td style='text-align:center;'>{0}</td></tr>", EXTENDED_AMOUNT);
            }
            //插入提货支付

            product.AppendFormat("<tr><td colspan=2>&nbsp</td><td colspan=2 style='text-align:center;'>提货支付:</td><td style='text-align:center;'>{0}</td></tr>",
                TOTAL_AMOUNT - DISC_AMOUNT - EXTENDED_AMOUNT);


            String orderdate = obj["ORDER_DATE"].ToString();
            orderdate = GetDateTime(orderdate, "", "yyyy年MM月dd日 HH:mm:ss");
            String deliverydate = obj["REQ_DELIVERY_DATE"].ToString();
            deliverydate = GetDateTime(deliverydate, "", "yyyy年MM月dd日");
            String printContent = String.Format(templete, obj["ORDER_NO"].ToString(),
                orderdate,
                deliverydate,
                obj["CONTACT_MAN"].ToString(),
                obj["CONTACT_LINK"].ToString(),
                obj["DELIVERY_ADDRESS"].ToString(),
                type, product.ToString(),

                 obj["ADDITIONAL_INFO"].ToString());
            //保存文件到待打印的列表中

            StreamWriter writer = null;
            System.IO.FileInfo file = new FileInfo(FileName);

            String PrintFileName = Properties.Settings.Default.PrintFolder + "Printing\\" + file.Name + ".htm";
            try
            {
                writer = File.CreateText(PrintFileName);
                writer.Write(printContent);
                writer.Flush();
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                    writer = null;
                }
            }
            this.AppendLog(String.Format("订单:{0}解析成功",obj["ORDER_NO"].ToString()));
            //生成该文件
            WebBrowser webBrowser = new WebBrowser();
            webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
            webBrowser.Url = new Uri(PrintFileName);
            webBrowser1.Url = webBrowser.Url;
            this.AppendLog(String.Format("提交订单{0}进行打印", obj["ORDER_NO"].ToString()));
            while (webBrowser.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
                System.Threading.Thread.Sleep(50);
            }
            webBrowser.Dispose();
            webBrowser = null;
            return true;
        }

        private void Run()
        {
            while (true)
            {
                if (fileList.Count > 0)
                {
                    String fileName = fileList.Dequeue();
                    if (!File.Exists(fileName))
                        continue;
                    if (fileName != null && !Print(fileName))
                    {
                        fileList.Enqueue(fileName);
                    }
                    
                }
            }
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            int count = 100;

            WebBrowser browser = ((WebBrowser)sender);
            try
            {
                browser.Print();

                //将文件移动到打印成功的文件夹
                FileInfo file = new FileInfo(browser.Url.LocalPath);
                String newfile = Properties.Settings.Default.PrintFolder + "Printed\\" + file.Name;
                if (File.Exists(newfile))
                    File.Delete(newfile);
                System.IO.File.Move(file.FullName, newfile);
                //删除原始文件
                File.Delete(Properties.Settings.Default.PrintFolder + file.Name.Replace(file.Extension, ""));
                this.AppendLog(String.Format("订单{0}打印成功", file.Name));
            }
            catch (Exception err)
            {
                this.AppendLog("错误信息：" + err.Message);
            }
            while (count-- > 0)
            {
                Application.DoEvents();
                System.Threading.Thread.Sleep(100);
            }

            
        }

        private void menuItemExit_Click(object sender, EventArgs e)
        {
            thread.Abort();
            thread = null;
            Application.Exit();

        }

        private void menuItemPrintSetup_Click(object sender, EventArgs e)
        {

        }

        private void frmPrinter_FormClosed(object sender, FormClosedEventArgs e)
        {
            menuItemExit_Click(sender, EventArgs.Empty);
        }
      
    }
}


